import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_2b_client/apis/MarketOrderApi.dart';
import 'package:flutter_2b_client/components/showConfirmDialog.dart';
import 'package:flutter_2b_client/store/EmployeeAuthorizationStore.dart';
import 'package:flutter_2b_client/utils/MobxHooks.dart';
import 'package:flutter_2b_client/utils/Page.dart';
import 'package:flutter_2b_client/utils/PagingUtils.dart';
import 'package:flutter_2b_client/utils/local_datetime.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:provider/provider.dart';

import '../components/GoodsListItem.dart';
import '../components/LoadingButton.dart';
import '../theme/custom_color.dart';
import '../utils/DeviceStorageUtils.dart';
import '../utils/ShareUtils.dart';
import '../utils/UIConstant.dart';

class MarketOrderDetailPage extends HookWidget {
  final int orderId;

  const MarketOrderDetailPage(this.orderId, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var scrollController = useScrollController();
    var marketOrderDetailState = useState<MarketOrderDetail?>(null);
    useEffect(() {
      marketOrderApi
          .getMarketOrderDetail(orderId)
          .then((value) => marketOrderDetailState.value = value);
      return null;
    }, [orderId]);

    var pagingController =
        usePagingController<Pageable, OrderItemInOrderSummary>(
            firstPageKey: Pageable());
    var totalElementsState = useState(0);
    usePagingControllerListener(
        pagingController,
        (pageable) => marketOrderApi
                .queryOrderItemsInOrder(orderId, pageable.toRequestParamsMap())
                .then((value) {
              totalElementsState.value = value.totalElements;
              return value;
            }),
        (item) => item.goodsId,
        [orderId]);
    final me = useObservable(
        () => Provider.of<EmployeeAuthorizationStore>(context).me);

    var showSubmitButton =
        marketOrderDetailState.value?.submitDateTime == null &&
            me?.hasAuthority("卖场_订单_下单") == true;

    var showAddButton = (me?.hasAuthority("卖场_订单_下单") == true &&
            marketOrderDetailState.value?.submitDateTime == null) ||
        (me?.hasAuthority("卖场_订单_转化为送货单") == true &&
            marketOrderDetailState.value?.deliveryDateTime == null);
    scrollToLast() {
      scrollController.animateTo((pagingController.itemList?.length ?? 0) * 80,
          duration: const Duration(milliseconds: 300), curve: Curves.ease);
    }

    var themeData = Theme.of(context);
    return Scaffold(
      bottomNavigationBar: showAddButton || showSubmitButton
          ? BottomAppBar(
              child: Row(
                children: [
                  if (showSubmitButton)
                    LoadingButton(
                      onPressed: () async {
                        await showConfirmDialog(context, onConfirm: () async {
                          await marketOrderApi.submitMarketOrder(orderId);
                          marketOrderDetailState.value = marketOrderDetailState
                              .value
                              ?.copyWith(submitDateTime: LocalDateTime.now());
                          if (context.mounted) {
                            Navigator.of(context).pop();
                          }
                        }, title: "是否确认", content: const Text("提交后等待业务员审核"));
                      },
                      child: const Text("提交订单"),
                    ),
                  if (showAddButton)
                    IconButton(
                        onPressed: () async {
                          var goodsId = await context.push(Uri(
                              path: "/goods",
                              queryParameters: {
                                "editMarketOrderId": orderId.toString()
                              }).toString()) as int?;
                          if (goodsId != null) {
                            var orderItemInOrderSummary = await marketOrderApi
                                .addItemFromGoodsId(orderId, goodsId);
                            pagingController.itemList =
                                pagingController.itemList?.toList()
                                  ?..add(orderItemInOrderSummary);
                            totalElementsState.value += 1;
                            Fluttertoast.showToast(
                              msg: "添加成功！${orderItemInOrderSummary.name}",
                            );
                            scrollToLast();
                          }
                        },
                        icon: const Icon(Icons.add)),
                ],
              ),
            )
          : null,
      floatingActionButton: showAddButton
          ? FloatingActionButton(
              onPressed: () async {
                var barcode = (await context.push(
                  Uri(
                    path: "/scanBarcode",
                    queryParameters: {
                      "marketOrderId": orderId.toString(),
                    },
                  ).toString(),
                )) as String?;
                if (barcode != null) {
                  var response =
                      await marketOrderApi.addItemFromBarcode(orderId, barcode);
                  var list = pagingController.itemList?.toList();
                  list?.add(response);
                  pagingController.itemList = list;
                  totalElementsState.value += 1;

                  Fluttertoast.showToast(
                    msg: "扫描成功！${response.name} ",
                  );
                  scrollToLast();
                }
              },
              child: const Icon(Icons.document_scanner),
            )
          : null,
      body: CustomScrollView(
        controller: scrollController,
        slivers: [
          SliverAppBar(
            expandedHeight: 200,
            pinned: true,
            title: const Text("订单详情"),
            actions: [
              PopupMenuButton(
                onSelected: (value) async {
                  var bytes = await marketOrderApi.exportToExcel(orderId);
                  final name =
                      "${marketOrderDetailState.value?.market.name ?? "卖场"}${marketOrderDetailState?.value?.createdDateTime.format("yyyy-MM-dd")}订单.xlsx";
                  switch (value) {
                    case 1:
                      if (context.mounted) {
                        await saveFileBytes(context, name, bytes);
                      }
                      break;
                    case 2:
                      if (context.mounted) {
                        await shareExcelFileByBytes(context, bytes, name);
                      }
                      break;
                    case 3:
                      if (context.mounted) {
                        showConfirmDialog(context,
                            content: const Text("删除后不可恢复"),
                            onConfirm: () async {
                          await marketOrderApi.deleteById(orderId);
                          if (context.mounted) {
                            Navigator.of(context).pop();
                            context.pop("DELETE");
                          }
                        }, title: "确定要删除此订单？");
                      }
                  }
                },
                itemBuilder: (BuildContext context) {
                  return [
                    ...shareAndExportMenuEntries,
                    if (marketOrderDetailState.value?.submitDateTime == null &&
                        me?.hasAuthority("卖场_订单_删除") == true)
                      PopupMenuItem(
                        value: 3,
                        child: Text(
                          '删除',
                          style: DefaultTextStyle.of(context)
                              .style
                              .copyWith(color: themeData.colorScheme.error),
                        ),
                      ),
                  ];
                },
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              background: Padding(
                padding: const EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "订单编号：${marketOrderDetailState.value?.number ?? ""}",
                    ),
                    Text(
                      "卖场：${marketOrderDetailState.value?.market.name ?? ""}",
                    ),
                    Text(
                      "创建时间：${marketOrderDetailState.value?.createdDateTime.format() ?? ""}",
                    ),
                    if (marketOrderDetailState.value?.submitDateTime != null)
                      Text(
                        "提交时间：${marketOrderDetailState.value?.submitDateTime?.format() ?? ""}",
                      ),
                    if (marketOrderDetailState.value?.deliveryDateTime != null)
                      Row(
                        children: [
                          const Text(
                            "已出货",
                          ),
                          TextButton(
                              onPressed: () {
                                context.push(
                                    "/markets/${marketOrderDetailState.value?.market.id}/deliveryOrders/$orderId");
                              },
                              child: const Text("出货单"))
                        ],
                      ),
                    Text(
                      "${totalElementsState.value}个单品",
                    ),
                  ],
                ),
              ),
            ),
          ),
          PagedSliverList(
            pagingController: pagingController,
            builderDelegate: PagedChildBuilderDelegate<OrderItemInOrderSummary>(
              itemBuilder: (BuildContext context, OrderItemInOrderSummary item,
                  int index) {
                return GestureDetector(
                  onTap: () {
                    context.push("/goods/${item.goodsId}");
                  },
                  onLongPress: () {
                    showConfirmDeleteGoodsDialog(
                      context,
                      onConfirm: () async {
                        await marketOrderApi.deleteOrderItem(
                            orderId, item.goodsId);
                        var newItemList = pagingController.itemList
                            ?.where(
                                (element) => element.goodsId != item.goodsId)
                            .toList();

                        if (pagingController.nextPageKey != null &&
                            pagingController.itemList != null) {
                          var queryPage =
                              await marketOrderApi.queryOrderItemsInOrder(
                                  orderId,
                                  Pageable(
                                          page:
                                              pagingController.itemList!.length,
                                          size: 1)
                                      .toRequestParamsMap());
                          newItemList?.addAll(queryPage.content);
                        }
                        pagingController.itemList = newItemList;
                        totalElementsState.value -= 1;
                        if (context.mounted) {
                          Navigator.of(context).pop();
                        }
                      },
                      barcode: item.barcode,
                      name: item.name,
                    );
                  },
                  child: MarketOrderItem(
                    orderId,
                    item,
                    onUpdateAmount: (amount) {
                      final newList = pagingController.itemList?.toList();
                      newList?[index] =
                          newList[index].copyWith(amountInOrder: amount);
                      pagingController.itemList = newList;
                    },
                    edited: showAddButton || showSubmitButton,
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endContained,
    );
  }
}

class MarketOrderItem extends HookWidget {
  final int orderId;
  final OrderItemInOrderSummary item;
  final Function(int amount) onUpdateAmount;
  final bool edited;

  const MarketOrderItem(this.orderId, this.item,
      {Key? key, required this.onUpdateAmount, this.edited = true})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GoodsListItem(
      onUpdateAmount: (int amount, int? unitId) async {
        final adjustedAmount = max(amount, 0);
        return marketOrderApi
            .updateOrderItemGoodsAmount(orderId, item.goodsId,
                UpdateItemAmountRequest(amount: adjustedAmount, unitId: unitId))
            .then((value) {
          Fluttertoast.showToast(
              msg: "修改成功",
              backgroundColor:
                  Theme.of(context).extension<CustomColors>()?.successContainer,
              textColor: Theme.of(context)
                  .extension<CustomColors>()
                  ?.onSuccessContainer);
          onUpdateAmount(adjustedAmount);
          return null;
        });
      },
      name: item.name,
      barcode: item.barcode,
      inStore: item.inStore,
      amount: item.amountInOrder,
      boxSpecification: item.boxSpecification,
      edited: edited,
      unit: item.unit,
      units: item.units,
    );
  }
}
